<template>
  <div class="main h-[calc(100%-29px)]">
    <el-card class="m-card relative w-full">
      <div
        v-if="status !== 'look' && activeName === 'first'"
        class="absolute right-[20px] top-[20px] z-10"
      >
        <el-button :icon="RefreshLeft" size="small" @click="reset"
          >重置</el-button
        >
        <el-button :icon="Check" size="small" type="primary" @click="submit"
          >保存</el-button
        >
      </div>
      <el-tabs
        v-model="activeName"
        class="demo-tabs"
        :before-leave="beforeLeave"
      >
        <el-tab-pane label="用户" name="first">
          <VppForm
            ref="first"
            v-loading="loading"
            :handleStatus="status"
            :form="form"
          />
        </el-tab-pane>
        <el-tab-pane label="终端" name="second">
          <VppTerminal
            :handleStatus="status"
            :activeVppUserId="activeVppUserId"
          />
        </el-tab-pane>
        <el-tab-pane label="储能" name="third">
          <VppStorage
            :handleStatus="status"
            :activeVppUserId="activeVppUserId"
          />
        </el-tab-pane>
        <el-tab-pane label="附件" name="four">
          <VppFile :handleStatus="status" :activeVppUserId="activeVppUserId" />
        </el-tab-pane>
        <el-tab-pane label="地图" name="five">
          <VppMap
            ref="vppMapRef"
            :vppUserData="form.data"
            :handleStatus="status"
            :activeVppUserId="activeVppUserId"
          />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import { Check, RefreshLeft } from "@element-plus/icons-vue";
import { nextTick, onMounted, reactive, ref, watch } from "vue";
import { useRoute } from "vue-router";
import {
  addVppUserList,
  editVppUserList,
  getVppUserDetail
} from "@/api/vppUser";
import VppForm from "./vppUserForm.vue";
import VppTerminal from "@/views/business/vppUser/vppTerminal.vue";
import VppStorage from "@/views/business/vppUser/vppStorage.vue";
import VppFile from "@/views/business/vppUser/vppFile.vue";
import VppMap from "@/views/business/vppUser/vppMap.vue";
import { ElMessage, ElNotification } from "element-plus";
import { cloneDeep } from "@pureadmin/utils";
const route = useRoute();
const status = ref("");
const activeVppUserId = ref("");
status.value = route.params.status;
activeVppUserId.value = route.params.vppUserId || "";
const first = ref(null);
const vppMapRef = ref(null);
const form = reactive({
  data: {
    id: null,
    name: null,
    fullName: null,
    address: null,
    siteAddress: null,
    groupName: null,
    districtId: null,
    area: null,
    sector: null,
    sectorInfo: null,
    dispatchName: null,
    gridVoltageLevel: null,
    substationName: null,
    powerBroker: null,
    distributionNo: null,
    govFundRate: null,
    capRate: null,
    capRefund: null,
    maxLoad: null,
    maxOutput: null,
    longitude: null,
    latitude: null,
    altitude: null,
    fenceXy: null,
    longitudeAndLatitude: null,
    inMarket: null,
    shareRatio: null,
    totalRevenue: null,
    shareRevenue: null,
    status: null,
    initOnlineTime: null,
    onlineTime: null,
    offlineTime: null,
    totalP: null,
    totalQ: null,
    totalEnergy: null,
    storageNum: null,
    terminalNum: null,
    equipNum: null,
    storageOnnum: null,
    terminalOnnum: null,
    equipOnnum: null,
    emsCode: null,
    hisCode: null,
    emsIpadd: null,
    hisIpadd: null,
    contactName: null,
    contactTel: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    gridRate: null
  },
  rules: {
    name: [{ required: true, message: "用户名称不能为空", trigger: "blur" }],
    fullName: [
      { required: true, message: "用户全称不能为空", trigger: "blur" }
    ],
    dispatchName: [
      { required: true, message: "上级调度名称不能为空", trigger: "blur" }
    ],
    gridVoltageLevel: [
      { required: true, message: "并网电压等级不能为空", trigger: "blur" }
    ],
    initOnlineTime: [
      { required: true, message: "首次上线时间不能为空", trigger: "blur" }
    ],
    onlineTime: [
      { required: true, message: "上线时间不能为空", trigger: "blur" }
    ],
    offlineTime: [
      { required: true, message: "下线时间不能为空", trigger: "blur" }
    ],
    contactName: [
      { required: true, message: "联系人不能为空", trigger: "blur" }
    ],
    contactTel: [
      { required: true, message: "联系电话不能为空", trigger: "blur" }
    ]
  }
});
const activeName = ref("first");
const beforeLeave = async (activeName, oldActiveName) => {
  let bool = await first.value.validateForm();
  if (status.value === "add" && !bool) {
    // 校验未通过
    ElMessage({
      message: "请填写完整用户信息并保存!",
      type: "error"
    });
    return false;
  }
  if (bool && (!activeVppUserId.value || activeVppUserId.value === "null")) {
    // 未保存
    ElMessage({
      message: "请先保存用户信息",
      type: "error"
    });
    return false;
  }
  if (bool) {
    if (activeName === "five") {
      if (!vppMapRef.value.map) {
        vppMapRef.value.showMap();
      } else {
        vppMapRef.value.echoMapData();
      }
    }
  }
  form.data = await getDetail(activeVppUserId.value);
  first.value.setForm(form.data);
  return bool;
};
const getDetail = id => {
  if (id && id !== "null") {
    return new Promise(async (resolve, reject) => {
      let data = await getVppUserDetail(id);
      resolve(data);
    });
  } else {
    return false;
  }
};
onMounted(async () => {
  if (status.value !== "add") {
    form.data = await getDetail(activeVppUserId.value);
  }
  first.value.setForm(form.data);
});
const loading = ref(false);
const submit = async () => {
  let bool = await first.value.validateForm();
  if (bool) {
    let data = first.value.getFormData();
    loading.value = true;

    if (status.value === "add") {
      if (
        activeVppUserId.value &&
        activeVppUserId.value !== "null" &&
        status.value === "add"
      ) {
        data.id = parseInt(activeVppUserId.value);
        await editVppUserList(data);
        ElNotification({
          title: "系统提示",
          message: "用户编辑成功",
          type: "success"
        });
      } else {
        let res = await addVppUserList(data);
        activeVppUserId.value = res.id + "";
        ElNotification({
          title: "系统提示",
          message: "用户创建成功",
          type: "success"
        });
      }
    } else {
      await editVppUserList(data);
      ElNotification({
        title: "系统提示",
        message: "用户编辑成功",
        type: "success"
      });
    }
    loading.value = false;
  }
};
const reset = () => {
  first.value.resetForm();
};
</script>
<style lang="scss" scoped>
:deep(.m-card .el-card__body) {
  display: flex;
  width: 100%;
  height: 100%;
}

.demo-tabs {
  display: flex;
  flex: 1;
  flex-direction: column;
  width: 100%;
  height: 100%;

  :deep(.el-tabs__content) {
    display: flex;
    flex: 1;

    .el-tab-pane {
      flex: 1;
      width: 100%;
    }
  }
}
</style>
